﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LeHouse.Server.Service;
using LeHouse.Server.Dto;
using LeHouse.Server.WebApi.Common;

namespace LeHouse.Server.WebApi.Controllers
{
    /// <summary>
    /// 项目跟踪与审核
    /// </summary>
    public class trackRecordController : ApiController
    {

        /// <summary>
        /// 显示项目跟踪信息(分页显示)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/trackRecord/select")]
        public SelectPager<dynamic> select([FromBody]SelectPager<Collateral_Personal> obj)
        {
            SelectPager<dynamic> sp = new SelectPager<dynamic>();
            Collateral_PersonalService personalService = new Collateral_PersonalService();
            var list = new List<dynamic>();
            if (string.IsNullOrEmpty(obj.search))
            {
                long totalSize;
                var d2 = new Collateral_PersonalService().SelectByPagerDesc(p => p.T_ReportNumber, obj.PageIndex, obj.PageSize, out totalSize).ToList();
                foreach (var x in d2)
                {
                    var d1 = new
                    {
                        personal = (from cps in new Collateral_PersonalService().Select(p => p.T_ReportNumber == x.T_ReportNumber) select new { cps.T_ReportNumber, cps.T_Date, cps.T_Iid, T_IidName = transmitHelper.getStaffByStaffID(cps.T_Iid) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_Iid).T_Name, cps.T_StartDate, cps.T_SiteSurveyid, T_SiteSurveyidName = transmitHelper.getStaffByStaffID(cps.T_SiteSurveyid) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_SiteSurveyid).T_Name, }).FirstOrDefault(),
                        borrower = new Collateral_BorrowerService().Select(p => p.T_ReportNumber == x.T_ReportNumber).ToList(),
                        StartToexamine = new Collateral_ToexamineService().Select(p => p.T_ReportNumber == x.T_ReportNumber && p.T_State == "成功" && p.T_Type == 0).FirstOrDefault(),
                        EndToexamine = (from cps in new Collateral_ToexamineService().Select(p => p.T_ReportNumber == x.T_ReportNumber && p.T_State == "成功" && p.T_Type == 1) select new { cps.T_date, cps.T_ToexaminePerson, T_ToexaminePersonName = transmitHelper.getStaffByStaffID(cps.T_ToexaminePerson) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_ToexaminePerson).T_Name }).FirstOrDefault()
                    };
                    list.Add(d1);
                }
                sp.Result = list.ToList<dynamic>();
                sp.PageCount = Convert.ToInt32(Math.Ceiling((double)totalSize/ obj.PageSize));
                sp.TotalSize = Convert.ToInt32(totalSize);
            }
            else
            {
                long totalSize;
                var d2 = new Collateral_PersonalService().SelectByPagerDesc(p=>p.T_ReportNumber.Contains(obj.search), p => p.T_ReportNumber, obj.PageIndex, obj.PageSize, out totalSize).ToList();
                foreach (var x in d2)
                {
                    var d1 = new
                    {
                        personal = (from cps in new Collateral_PersonalService().Select(p => p.T_ReportNumber == x.T_ReportNumber) select new { cps.T_ReportNumber, cps.T_Date, cps.T_Iid, T_IidName = transmitHelper.getStaffByStaffID(cps.T_Iid) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_Iid).T_Name, cps.T_StartDate, cps.T_SiteSurveyid, T_SiteSurveyidName = transmitHelper.getStaffByStaffID(cps.T_SiteSurveyid) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_SiteSurveyid).T_Name, }).FirstOrDefault(),
                        borrower = new Collateral_BorrowerService().Select(p => p.T_ReportNumber == x.T_ReportNumber).ToList(),
                        StartToexamine = new Collateral_ToexamineService().Select(p => p.T_ReportNumber == x.T_ReportNumber && p.T_State == "成功" && p.T_Type == 0).FirstOrDefault(),
                        EndToexamine = (from cps in new Collateral_ToexamineService().Select(p => p.T_ReportNumber == x.T_ReportNumber && p.T_State == "成功" && p.T_Type == 1) select new { cps.T_date, cps.T_ToexaminePerson, T_ToexaminePersonName = transmitHelper.getStaffByStaffID(cps.T_ToexaminePerson) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_ToexaminePerson).T_Name }).FirstOrDefault()
                    };
                    list.Add(d1);
                }
                sp.Result = list.ToList<dynamic>();
                sp.PageCount = Convert.ToInt32(Math.Ceiling((double)totalSize / obj.PageSize));
                sp.TotalSize = Convert.ToInt32(totalSize);
            }
            return sp;
            
            
        }



        ///  <summary>
        ///  显示审核列表（根据报告编号查询）
        ///  </summary>
        ///  <param name="S_name"></param>
        ///  <returns></returns>
        [HttpPost]
        [Route("api/trackRecord/examinationSelect")]
        public List<Collateral_Personal> examinationSelect([FromBody]string T_ReportNumber)
        {
            Collateral_PersonalService personalservice = new Collateral_PersonalService();
            if (string.IsNullOrEmpty(T_ReportNumber))
            {
                var d1 = personalservice.Select(p => p.T_State > 2).OrderByDescending(p => p.T_ReportNumber).ToList();
                return d1;
            }
            else
            {
                var d1 = personalservice.Select().Where(p => (p.T_State > 2) && (p.T_ReportNumber.Contains(T_ReportNumber))).OrderByDescending(p => p.T_ReportNumber).ToList();
                return d1;
            }
        }

        /// <summary>
        /// 审核列表（分页显示）
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/trackRecord/examinationSelectPage")]
        public SelectPager<dynamic> examinationSelectPage([FromBody]SelectPager<Collateral_Personal> obj)
        {
            SelectPager<dynamic> sp = new SelectPager<dynamic>();
            Collateral_PersonalService personalService = new Collateral_PersonalService();
            if (string.IsNullOrEmpty(obj.search))
            {
                long totalSize;
                var result = (from cps in personalService.SelectByPagerDesc(p => p.T_State > 2, p => p.T_ReportNumber, obj.PageIndex, obj.PageSize, out totalSize)
                              select new
                              {
                                  cps.T_FinalAuditNumber,
                                  cps.T_ReportNumber,
                                  cps.T_Loanlimit,
                                  cps.T_Actual,
                                  cps.T_Located,
                                  T_PurposeID = EnumHelperDic.GetEnumSelectState<EnumSelectType>(cps.T_PurposeID),
                                  cps.T_Activate,
                                  T_ReportID = EnumHelperDic.GetEnumSelectState<EnumSelectType>(cps.T_ReportID),
                                  cps.T_Linkman,
                                  cps.T_Phone,
                                  cps.T_Loanyear,
                                  cps.T_Assess,
                                  cps.T_DepartmentID,
                                  cps.T_SiteSurveyid,
                                  T_DepartmentIDText = transmitHelper.getDepartmentByDid(cps.T_DepartmentID) == null ? "" : transmitHelper.getDepartmentByDid(cps.T_DepartmentID).T_Dname,
                                  T_SiteSurveyidText = transmitHelper.getStaffByStaffID(cps.T_SiteSurveyid)==null?"":transmitHelper.getStaffByStaffID(cps.T_SiteSurveyid).T_Name,
                                  T_Iid = transmitHelper.getStaffByStaffID(cps.T_Iid) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_Iid).T_Name,
                                  cps.T_Date,
                                  cps.T_State,
                                  T_StateText = EnumHelperDic.GetEnumSelectState<EnumSelectState>(cps.T_State),
                                  cps.T_StartDate,
                                  cps.T_EndDate,
                                  cps.T_FirstIdea,
                                  cps.T_LastIdea,
                                  T_ValuationPurpose = EnumHelperDic.GetEnumSelectState<EnumSelectType>(Convert.ToInt32(cps.T_ValuationPurpose)),
                                  T_ValuationName = transmitHelper.getStaffByStaffID(Convert.ToInt32(cps.T_ValuationName)) == null ? "" : transmitHelper.getStaffByStaffID(Convert.ToInt32(cps.T_ValuationName)).T_Name,
                                  cps.T_ValuationDate,
                                  cps.T_ValuationPrice,
                                  cps.T_Builtuparea,
                                  cps.T_Valueofassessment,
                                  cps.T_Mortgageriskrate,
                                  cps.T_MaximumMortgage,
                                  cps.T_ValuationCalculation,
                                  cps.T_Survey
                              });
                sp.Result = result.ToList<dynamic>();
                int count = personalService.Select(p => p.T_State > 2).ToList().Count();
                sp.PageCount = Convert.ToInt32(Math.Ceiling((double)count / obj.PageSize));
                sp.TotalSize = Convert.ToInt32(count);
            }
            else
            {
                long totalSize;
                var result = (from cps in personalService.SelectByPagerDesc(p => p.T_State > 2 && p.T_ReportNumber.Contains(obj.search), p => p.T_ReportNumber, obj.PageIndex, obj.PageSize, out totalSize)
                              select new
                              {
                                  cps.T_FinalAuditNumber,
                                  cps.T_ReportNumber,
                                  cps.T_Loanlimit,
                                  cps.T_Actual,
                                  cps.T_Located,
                                  T_PurposeID = EnumHelperDic.GetEnumSelectState<EnumSelectType>(cps.T_PurposeID),
                                  cps.T_Activate,
                                  T_ReportID = EnumHelperDic.GetEnumSelectState<EnumSelectType>(cps.T_ReportID),
                                  cps.T_Linkman,
                                  cps.T_Phone,
                                  cps.T_Loanyear,
                                  cps.T_Assess,
                                  cps.T_DepartmentID,
                                  cps.T_SiteSurveyid,
                                  T_DepartmentIDText = transmitHelper.getDepartmentByDid(cps.T_DepartmentID) == null ? "" : transmitHelper.getDepartmentByDid(cps.T_DepartmentID).T_Dname,
                                  T_SiteSurveyidText = transmitHelper.getStaffByStaffID(cps.T_SiteSurveyid) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_SiteSurveyid).T_Name,
                                  T_Iid = transmitHelper.getStaffByStaffID(cps.T_Iid) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_Iid).T_Name,
                                  cps.T_Date,
                                  cps.T_State,
                                  T_StateText = EnumHelperDic.GetEnumSelectState<EnumSelectState>(cps.T_State),
                                  cps.T_StartDate,
                                  cps.T_EndDate,
                                  cps.T_FirstIdea,
                                  cps.T_LastIdea,
                                  T_ValuationPurpose = EnumHelperDic.GetEnumSelectState<EnumSelectType>(Convert.ToInt32(cps.T_ValuationPurpose)),
                                  T_ValuationName = transmitHelper.getStaffByStaffID(Convert.ToInt32(cps.T_ValuationName)) == null ? "" : transmitHelper.getStaffByStaffID(Convert.ToInt32(cps.T_ValuationName)).T_Name,
                                  cps.T_ValuationDate,
                                  cps.T_ValuationPrice,
                                  cps.T_Builtuparea,
                                  cps.T_Valueofassessment,
                                  cps.T_Mortgageriskrate,
                                  cps.T_MaximumMortgage,
                                  cps.T_ValuationCalculation,
                                  cps.T_Survey
                              });
                sp.Result = result.ToList<dynamic>();
                int count = personalService.Select(p => p.T_State > 2 && p.T_ReportNumber.Contains(obj.search)).ToList().Count();
                sp.PageCount = Convert.ToInt32(Math.Ceiling((double)count / obj.PageSize));
                sp.TotalSize = Convert.ToInt32(count);
            }
            return sp;
        }


        

        /// <summary>
        /// 初审
        /// </summary>
        /// <param name="S_name"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/trackRecord/FirstIdea")]
        public dynamic FirstIdea([FromBody]Collateral_Personal obj)
        {
            jsonManager jm = new jsonManager();
            Collateral_PersonalService personalservice = new Collateral_PersonalService();
            Collateral_BorrowerService borrowerservice = new Collateral_BorrowerService();
            Collateral_Toexamine toexamine = new Collateral_Toexamine();
            PersonalOrToexamine personalOrToexamine = new PersonalOrToexamine();

            var d1 = personalservice.Select().Where(p => p.T_ReportNumber == obj.T_ReportNumber).FirstOrDefault();
            if (d1 == null)
            {
                jm.code = 0;
                jm.msg = "根据该评估报告编号找不到信息！";
                return Json(jm);
            }


            if (d1.T_State != 3 && d1.T_State != 4 && d1.T_State!= 6)
                {
                    jm.code = 0;
                    jm.msg = "当前状态不能初审！";
                    return Json(jm);
                }
                d1.T_State = Convert.ToInt32(obj.T_State);
                toexamine.T_ReportNumber = obj.T_ReportNumber;
                toexamine.T_FirstIdea = obj.P_firstIdea;
                toexamine.T_State = obj.T_State == 5 ? "通过" : "不通过";
                toexamine.T_date = DateTime.Now;
                toexamine.T_Type = 0;
                toexamine.T_ToexaminePerson = obj.T_Iid;
            
               
            personalOrToexamine.Toexamine = toexamine;
            personalOrToexamine.Personal = d1;

            if (personalservice.PersonalUpdateAndToexamineInsert(personalOrToexamine))
            {
                jm.code = 1;
                jm.msg = "审核成功";
                return Json(jm);//代表审核成功
            }
            else
            {
                jm.code = 0;
                jm.msg = "执行审核，在最终修改数据时报错！";
                return Json(jm);
            }

        }

        /// <summary>
        /// 终审
        /// </summary>
        /// <param name="S_name"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/trackRecord/LastIdea")]
        public dynamic LastIdea([FromBody]Collateral_Personal obj)
        {
            jsonManager jm = new jsonManager();
            Collateral_PersonalService personalservice = new Collateral_PersonalService();
            Collateral_BorrowerService borrowerservice = new Collateral_BorrowerService();
            Collateral_Toexamine toexamine = new Collateral_Toexamine();
            PersonalOrToexamine personalOrToexamine = new PersonalOrToexamine();

            var d1 = personalservice.Select().Where(p => p.T_ReportNumber == obj.T_ReportNumber).FirstOrDefault();
            if (d1 == null)
            {
                jm.code = 0;
                jm.msg = "根据该评估报告编号找不到信息！";
                return Json(jm);
            }

                if (d1.T_State != 5 && d1.T_State != 6)
                {
                    jm.code = 0;
                    jm.msg = "当前状态不能终审！";
                    return Json(jm);
                }
                d1.T_State = Convert.ToInt32(obj.T_State);
                toexamine.T_ReportNumber = obj.T_ReportNumber;
                toexamine.T_FirstIdea = obj.P_firstIdea;
                toexamine.T_State = obj.T_State == 7 ? "通过" : "不通过";
                toexamine.T_date = DateTime.Now;
                toexamine.T_Type = 1;
                toexamine.T_ToexaminePerson = obj.T_Iid;
            
            personalOrToexamine.Toexamine = toexamine;
            personalOrToexamine.Personal = d1;

            if (personalservice.PersonalUpdateAndToexamineInsert(personalOrToexamine))
            {
                jm.code = 1;
                jm.msg = "审核成功";
                return Json(jm);//代表审核成功
            }
            else
            {
                jm.code = 0;
                jm.msg = "执行审核，在最终修改数据时报错！";
                return Json(jm);
            }

        }


        /// <summary>
        ///根据项目编号显示审核记录
        /// </summary>
        /// <param name="T_ReportNumber"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/trackRecord/TrialInfo")]
        public dynamic TrialInfo([FromBody]SelectPager<Collateral_Toexamine> obj)
        {
            SelectPager<dynamic> sp = new SelectPager<dynamic>();
            Collateral_ToexamineService toexamineService = new Collateral_ToexamineService();
            System_StaffService staffService = new System_StaffService();
            long totalSize;
            var result = (from cps in toexamineService.SelectByPagerDesc(p => p.T_ReportNumber == obj.search, p => p.T_date, obj.PageIndex, obj.PageSize, out totalSize)
                          select new
                          {
                              cps.T_ReportNumber,
                              cps.T_FirstIdea,
                              cps.T_State,
                              T_date = cps.T_date.ToString("yyyy-MM-dd hh:mm:ss"),
                              cps.T_ToexaminePerson,
                              T_ToexaminePersonText = transmitHelper.getStaffByStaffID(cps.T_ToexaminePerson) == null ? "" : transmitHelper.getStaffByStaffID(cps.T_ToexaminePerson).T_Name,
                              cps.T_Type,
                              T_TypeText = cps.T_Type == 0 ? "初审" : "终审",
                          });
             sp.Result = result.ToList<dynamic>();
             int count = toexamineService.Select(p => p.T_ReportNumber == obj.search).ToList().Count();
             sp.PageCount = Convert.ToInt32(Math.Ceiling((double)count / obj.PageSize));
             sp.TotalSize = Convert.ToInt32(count);

             return sp;
        }


        /// <summary>
        /// 获取枚举定义的状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("api/trackRecord/GetSelectState")]
        public dynamic GetSelectState()
        {
            var dropDic = EnumHelperDic.EnumListDic<EnumSelectState>(-1, "--请选择--");
            return Json(dropDic);
        }


    }


}
